package com.xinchili.autoddl.autoClass.util;

import java.util.*;

import java.lang.reflect.Field;

public class CommontUtil {

    /**
     * 驼峰转下划线
     * 首字母大写不转换
     *
     * @param name 类属性字段名
     * @return 转换后的字符串
     */
    public static String camelToUnderline(String name) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (Character.isUpperCase(c)) {
                // 如果不是第一个字符，则添加下划线
                if (i > 0) {
                    result.append("_");
                }
                result.append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    /**
     *
     * @param clazz
     * @return
     */
    public static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != Object.class && clazz != null) {
            Collections.addAll(fields, clazz.getDeclaredFields());
            clazz = clazz.getSuperclass();
        }
        return fields;
    }
}
